package org.nokatag.tagjava;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.nokatag.common.HtmlToText;

/**
 * html截取子串，先清除html标签后在截取
 * @author rebin
 *
 */
public class HtmlSubString extends BodyNokaTag{

	private static final long serialVersionUID = -6156499848136829752L;
	private Integer len = null;//截取的长度
	private Integer start = 0;//开始截取的字符串
	private String format=null;//格式化字符串
	
	
	public int doStartTag()throws JspException{
		return EVAL_BODY_BUFFERED;
	}
	
	public int doAfterBody() throws JspException {
        BodyContent body = this.getBodyContent();
        String    content = body.getString();
        try{
        	if(null!=content && content.length()>1){
        		String bs = HtmlToText.subFromHtml(content,start,len);
        		if(null!=format && format.trim().length()>1){
            		bs=String.format(format,bs);
            	}
        		body.clearBody();
     	        body.write(bs);
     	        setBodyContent(body);
        	}
        }catch(Exception se){
        	se.printStackTrace();
        }
        return SKIP_BODY;
    }
    
    public int doEndTag()throws JspException{  
        if(super.bodyContent!=null){  
            try{  
                super.bodyContent.writeOut(super.getPreviousOut());    //输出到页面  
            }  
            catch(Exception e){}  
        }  
        return BodyTagSupport.EVAL_PAGE;  
    }

	public Integer getLen() {
		return len;
	}

	public void setLen(Integer len) {
		this.len = len;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}
}
